package rejjie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

// 定义拦截器会拦截哪些注解
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    //java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '123' for key 'employee.idx_username'
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        // 展示错误
       log.error(ex.getMessage());

       // 错误信息是否包含这些信息
       if(ex.getMessage().contains("Duplicate entry")){
           String[] s = ex.getMessage().split(" ");
           // 得到用户名 拼接错误信息返回
           String msg = s[2]+"已存在";
           return R.error(msg);
       }
        return R.error("未知错误");
        }

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }


}
